import { useEffect, useReducer } from 'react'

import TodoAdd from './components/TodoAdd'
// import TodoList from './components/TodoList'
import TodoFooter from './components/TodoFooter'
import MainSection from './components/MainSection'

import TodoContext from './TodoContext'

import reducer from './reducer'

// 导入todos样式
import './App.css'
import { TodoItem } from './todos'

const initialState = [{ id: 1, text: '吃饭', done: false }]

const useTodos = (initialState: TodoItem[]) => {
  // const [todos, setTodos] = useState(initialState)
  const [todos, dispatch] = useReducer(reducer, initialState)

  // 读取 localStorage 中的数据
  useEffect(() => {
    const res = localStorage.getItem('todos')

    if (res) {
      const resTodos = JSON.parse(res)
      dispatch({ type: 'loadData', payload: resTodos })
    }
  }, [])

  // 保存最新的 todos 数据到 localStorage 中
  useEffect(() => {
    localStorage.setItem('todos', JSON.stringify(todos))
  }, [todos])

  // 获取到添加的任务
  const onAdd = (text: string) => {
    dispatch({ type: 'add', payload: text })
  }

  // 切换任务完成状态
  const onToggle = (id: number) => {
    dispatch({ type: 'toggle', payload: id })
  }

  // 删除任务
  const onDelete = (id: number) => {
    dispatch({ type: 'delete', payload: id })
  }

  return { todos, onAdd, onToggle, onDelete }
}

const App = () => {
  const { todos, onToggle, onDelete, onAdd } = useTodos(initialState)

  return (
    <section className="todoapp">
      {/* 添加任务 */}
      <TodoAdd onAddTodo={onAdd} />

      {/* <section className="main">
        <input id="toggle-all" className="toggle-all" type="checkbox" />
        <label htmlFor="toggle-all">Mark all as complete</label>
        <TodoList list={todos} onToggleTodo={onToggle} onDeleteTodo={onDelete} />
      </section> */}

      <TodoContext.Provider value={{ todos, onToggleTodo: onToggle, onDeleteTodo: onDelete }}>
        <MainSection></MainSection>
      </TodoContext.Provider>

      {/* footer 组件 */}
      <TodoFooter />
    </section>
  )
}

export default App
